﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class MethodDebugInformationRule : ILRule<MethodDebugInformationHandle>
    {
        [ILInfo(true, ILInfoParseMethod.AsEntityHandle)]
        public DocumentHandle Document { get; }

        [ILInfo]
        public byte[] SequencePoints { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandle)]
        public StandaloneSignatureHandle LocalSignature { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public SequencePointCollection SequencePointCollection { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandle)]
        public MethodDefinitionHandle StateMachineKickoffMethod { get; }

        public MethodDebugInformationRule(
            DocumentHandle document,
            byte[] sequencePoints)
            : base()
        {
            Document = document;
            SequencePoints = sequencePoints;
        }

        public MethodDebugInformationRule(MetadataReader reader, MethodDebugInformationHandle methodDebugInformationHandle)
            : base(reader)
        {
            MethodDebugInformation methodDebugInformation = reader.GetMethodDebugInformation(methodDebugInformationHandle);
            Document = methodDebugInformation.Document;
            SequencePoints = reader.GetBlobBytes(methodDebugInformation.SequencePointsBlob);
            LocalSignature = methodDebugInformation.LocalSignature;
            SequencePointCollection = methodDebugInformation.GetSequencePoints();
            StateMachineKickoffMethod = methodDebugInformation.GetStateMachineKickoffMethod();
        }

        public override MethodDebugInformationHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddMethodDebugInformation(
                document: Document,
                sequencePoints: SequencePoints == null ? default : builder.GetOrAddBlob(SequencePoints));
        }
    }
}